﻿
CREATE PROCEDURE [dbo].[proc_Finance_RunningAccount_UpdateOrder_G]
	(	
		@Id VARCHAR(1000),
		@OrderId nvarchar(50),
		@PayId int
	)
AS
BEGIN

	BEGIN TRANSACTION--开始事务
DECLARE @errorSun INT --定义错误计数器
SET @errorSun=0 --没错为0

--By GSJ 2012-08-14 将16:30后的数据调整到第2天 Begin--
	Declare @nDays int,@nHour int,@nMinute int,@dToday DateTime
	--Set @dToday = GETDATE() --初始化日期
	----16:30分调整日期
	--Set @nHour = 16
	--Set @nMinute = 30

	----今天+1天与下月1日进行比较，相同则说明今天是本月最后1天
	--If Month(GetDate())<12
	--	Set @nDays=DateDiff(d,DateAdd(d,1,GetDate()),Convert(datetime,Convert(varchar(4),Year(GetDate())) + '-' + Convert(varchar(2),Month(GetDate())+1) + '-1'))
	--Else
	--	Set @nDays=DateDiff(d,DateAdd(d,1,GetDate()),Convert(datetime,Convert(varchar(4),Year(GetDate())+1) + '-01-01'))
	--If @nDays>0 --不是最后1天
	--Begin
	--	If DatePart(hh,GETDATE())>@nHour Or (DatePart(hh,GETDATE())=@nHour And DatePart(mi,GETDATE())>@nMinute)	--超过16:30分
	--		Set @dToday = DateAdd(hh,12,GETDATE())	--加12小时
	--END
	Set @dToday=dbo.Get_SetDateTime()
--By GSJ 2012-08-14 将16:30后的数据调整到第2天 End -- 
--               

--By ZHT 2012-02-28取该客户上一成单(如果有)的跟进客服
	Declare @TrackKfDepId int,@TrackKfName nvarchar(30),@TrackKfAccount varchar(30),@TrackBDName nvarchar(30),@TrackBDAccount varchar(30)
	--初始化 跟进客服的部门编号、姓名、账号
	Set @TrackKfDepId=0
	Set @TrackKfName=''
	Set @TrackKfAccount=''
	set @TrackBDName=''
	Set @TrackBDAccount=''

	select @TrackKfDepId=isnull((select departmentid from employee where employee.username=customer.ServicePerson),0),@TrackKfName=isnull(ServicePersonEName,''),@TrackKfAccount=isnull(ServicePerson,'')
			,@TrackBDName=isnull(BDServicePersonEName,''),@TrackBDAccount=isnull(BDServicePerson,'') from customer
		where customerid =(select cusid from [order] where oid=@OrderId)

--看此客服是否已离职(非常规成单不会执行这段)
	--Declare @state int
	--If (@TrackKfDepId Is Not Null) And (@TrackKfName Is Not Null) And (@TrackKfAccount Is Not Null)
	--	Begin
	--		Select Top 1 @state=[state] From employee Where username=@TrackKfAccount
	--		If @state=5 Or (@state Is Null)
	--		Begin
	--			Set @TrackKfDepId=null
	--			Set @TrackKfName=null
	--			Set @TrackKfAccount=null
	--		End	
	--	End
--End 取跟进客服

    declare @c int
    DECLARE @sqlstr VARCHAR(1000)
		PRINT @Id
	/* 修改Order_PaymentRecord表中的RID（[Finance_RunningAccount]中的ID） */
	/*2015.1.4  增加条件 and Order_PaymentRecord.FinanceFlag=0 认领过的首款不能再次认领，防止两人认同笔首款GSJ*/
	SET @sqlstr ='UPDATE Order_PaymentRecord 
	SET
	Order_PaymentRecord.Rid=frac.RId,
	Order_PaymentRecord.Prices=frac.Income,
	Order_PaymentRecord.FinanceFlag=1,
	Order_PaymentRecord.FinanceDate='''+CONVERT(varchar, @dToday, 120 )+'''
	FROM ( select sum(Income) as Income,max(RId) as RId from  Finance_RunningAccountCopy  where id IN ('+@Id+') ) AS frac 
	WHERE Order_PaymentRecord.Id='+Convert(varchar,@PayId)+' and Order_PaymentRecord.FinanceFlag=0 ' --frac.id=@Id
	/* 修改Order_PaymentRecord表中的RID（[Finance_RunningAccount]中的ID）END */
	EXEC (@sqlstr)
	
	if @@ROWCOUNT<1
		begin
			set @errorSun=@errorSun+1		
			goto e;
		end
	PRINT @sqlstr   
	                             --
	/* 修改[Finance_RunningAccount]表中的Renling（认领状态），改为已认领,OrderId(记单号)  */
	SET @sqlstr ='UPDATE [Finance_RunningAccount] SET Renling = 2,RenlingTime='''+CONVERT(varchar,@dToday,120)+''',OrderId = '''+@OrderId+''',isGreen=1 WHERE Finance_RunningAccount.id in (SELECT  Finance_RunningAccountCopy.RId from Finance_RunningAccountCopy WHERE Finance_RunningAccountCopy.id IN ('+@Id+') )'
	/* 修改[Finance_RunningAccount]表中的Renling（认领状态），改为已认领,OrderId(记单号) END */
	EXEC (@sqlstr)
	

		if @@ROWCOUNT<1
		begin
			set @errorSun=@errorSun+1		
			goto e;
		end
	 	PRINT @sqlstr
	
	--修改订单表
--	SET @sqlstr ='Update [Order] Set 
--		StateId=2,
--		ShiShouPrice=(Select Sum(Prices) From Order_PaymentRecord Where OId=[Order].OId and FinanceFlag=1),
--		FinanceRenlingDate=GetDate(),
--		flag=0
--	Where OId='''+@OrderId +''''
--By ZHT 2012-03-03 生成订单编号开始--
Declare @rq varchar(10),@shl int,@bh char(12)
Set @rq=Convert(varchar(10),getdate(),112)
Select @shl=Count(0) From [order] Where Left(OrderId,8)=@rq
If @shl=0
	Set @bh=@rq+'0001'
Else
	Begin
		Set @shl=@shl+1
		Set @bh=@rq+replicate('0',4-len(@shl))+convert(varchar(4),@shl)
	End
--By ZHT 2012-03-03 生成订单编号结束--
--By ZHT 2012-04-23 非企成单不产生订单编号--
--FinanceRenlingDate='''+CONVERT(varchar, @dToday, 120 )+''',
Declare @NOE_Flag int
Select @NOE_Flag=NOE_Flag From [order] Where OId=@OrderId
If @NOE_Flag<>0	--非常规成单
	begin 
		Set @bh=''	--编号置空
		SET @sqlstr ='Update [Order] Set 
			ShiShouPrice=(Select Sum(Prices) From Order_PaymentRecord Where OId=[Order].OId and FinanceFlag=1),
			flag=0,OrderId='''+@bh+'''		
			Where OId='''+@OrderId +''''
	end
--By ZHT 2012-04-23--
--By ZHT 2012-02-28--
--If (@TrackKfDepId Is Null) Or (@TrackKfName Is Null) Or (@TrackKfAccount Is Null)
--	SET @sqlstr ='Update [Order] Set 
--		ShiShouPrice=(Select Sum(Prices) From Order_PaymentRecord Where OId=[Order].OId and FinanceFlag=1),
--		FinanceRenlingDate='''+CONVERT(varchar, @dToday, 120 )+''',flag=0,OrderId='''+@bh+'''
--		Where OId='''+@OrderId +''''
--Else
--	SET @sqlstr ='Update [Order] Set 
--		ShiShouPrice=(Select Sum(Prices) From Order_PaymentRecord Where OId=[Order].OId and FinanceFlag=1),
--		FinanceRenlingDate='''+CONVERT(varchar, @dToday, 120 )+''',flag=0,OrderId='''+@bh+'''
--		,TrackKfDepId='+Convert(varchar(10),@TrackKfDepId)+',TrackKfName='''+@TrackKfName+''',TrackKfAccount='''+@TrackKfAccount+'''
--		Where OId='''+@OrderId +''''
--FinanceRenlingDate='''+CONVERT(varchar, @dToday, 120 )+''',
else
begin
    SET @sqlstr ='Update [Order] Set 
		ShiShouPrice=(Select Sum(Prices) From Order_PaymentRecord Where OId=[Order].OId and FinanceFlag=1),
		flag=0,OrderId='''+@bh+'''
		,TrackKfDepId='+Convert(varchar(10),@TrackKfDepId)+',TrackKfName='''+@TrackKfName+''',TrackKfAccount='''+@TrackKfAccount+'''
		,TrackBDAccount='''+@TrackBDAccount+''',TrackBDName='''+@TrackBDName+'''
		Where OId='''+@OrderId +''''
end


--By ZHT 2012-02-28--
--绿色通道的成单在认款时已经参与应收和成单总额的计算，认首款时认领时间不能变，否则成单额会虚增，
--不是绿色通道时正常修改认领时间
--3.17 GSJ
DECLARE @flag INT,@stateid int --是否是绿色通道
SELECT @flag=isgreen,@stateid=StateId FROM [Order] WHERE OId=@OrderId
IF @flag=0 --不是绿色通道,改成单状态，认领时间
BEGIN
	UPDATE [Order] set StateId=2,FinanceRenlingDate=@dToday WHERE  OId=@OrderId
END
ELSE
	BEGIN 
		IF @stateid=1 --是绿色通道成单，但是未分析
		BEGIN
			UPDATE [Order] SET StateId=2 WHERE OId=@OrderId 
		END		
	END

	EXEC (@sqlstr)
		
		if @@ROWCOUNT<1
		begin
			set @errorSun=@errorSun+1		
			goto e;
		end
	--PRINT @sqlstr 
	
	--删除中间数据
	SET @sqlstr ='Delete From Finance_RunningAccountCopy Where  Id IN ('+@Id+')' --Id=@Id	
	EXEC (@sqlstr)
	
		if @@ROWCOUNT<1
		begin
			set @errorSun=@errorSun+1		
			goto e;
		end
	PRINT @sqlstr 
	 
	--不再添加新的Order_PaymentRecord记录，所以不用将老记录删除 
	--Delete From Order_PaymentRecord Where Id=@PayId
	
	--IF @errorSun<>0
	--BEGIN
	--	PRINT '有错误，回滚'
	--	ROLLBACK TRANSACTION--事务回滚语句
	--END
	--ELSE
	--	BEGIN
	--	PRINT '成功，提交'
	--	COMMIT TRANSACTION--事务提交语句
	--	END                  

 e:
    PRINT @errorSun
	if @errorSun>0
	begin
		rollback TRANSACTION
	end
	else
	begin

		commit TRANSACTION

	END
	
	if @shl%10=0 
	begin
       exec [dbo].[_UpdateOrder]   
    end
end



	RETURN


